<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>WebSocket Example</title>
</head>

<body>
  <h1>WebSocket Example</h1>
  <button id="sendButton">Send Message</button>
  <div id="messages"></div>

  <script>
    // 创建 WebSocket 连接
    const socket = new WebSocket('ws://localhost:3001');

    // 监听连接打开事件
    socket.addEventListener('open', function (event) {
      console.log('连接已建立');
      document.getElementById('messages').innerHTML += '<p>连接已建立</p>';
    });

    // 监听消息事件
    socket.addEventListener('message', function (event) {
      console.log('消息来自服务器:', event.data);
      document.getElementById('messages').innerHTML += `<p>服务器: ${event.data}</p>`;
    });

    // 监听错误事件
    socket.addEventListener('error', function (event) {
      console.error('WebSocket 错误:', event);
      document.getElementById('messages').innerHTML += `<p style="color: red;">WebSocket 错误: ${event.message}</p>`;
    });

    // 监听连接关闭事件
    socket.addEventListener('close', function (event) {
      console.log('连接已关闭');
      document.getElementById('messages').innerHTML += '<p>连接已关闭</p>';
    });

    // 发送消息按钮点击事件
    document.getElementById('sendButton').addEventListener('click', function () {
      const message = 'Hello Server!';
      socket.send(message);
      document.getElementById('messages').innerHTML += `<p>客户端: ${message}</p>`;
    });
  </script>
</body>

</html>